#==============================================================================
#
#  $Id$
#
"""
    Utilities used in more than one test script.
"""
#
#   Copyright (C) 2006 Michael A. Muller
#   Portions Copyright (C) 2008 Google Inc.
#
#   This file is part of ODB.
#
#   ODB is free software: you can redistribute it and/or modify it under the 
#   terms of the GNU Lesser General Public License as published by the Free 
#   Software Foundation, either version 3 of the License, or (at your option) 
#   any later version.
#
#   ODB is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License 
#   along with ODB.  If not, see <http://www.gnu.org/licenses/>.
#
#==============================================================================

import shutil, unittest
from odb.full import FullEnv

class SortedList(list):
    """
        A sorted list of key-value pairs - useful for keeping track of the 
        contents of a b-tree.
    """
   
    def __bsearch(self, key, start, end):
        """
            Binary search a range of the list for the given key.  Returns the 
            index of where the key belongs.
        """
        if start == end:
            return start
        
        mid = start + (end - start) / 2
        if key > self[mid][0]:
            return self.__bsearch(key, mid + 1, end)
        else:
            return self.__bsearch(key, start, mid)
       
    def add(self, key, val):
        i = self.__bsearch(key, 0, len(self))
        self.insert(i, (key, val))
    
    def remove(self, key):
        i = self.__bsearch(key, 0, len(self))
        if self[i][0] == key:
            del self[i]
        else:
            raise KeyError(key)
    
    def replace(self, key, val):
        i = self.__bsearch(key, 0, len(self))
        self[i] = (key, val)

class DBTest(unittest.TestCase):
    """
        Base class for everything that creates a database in setUp() and 
        deletes it in tearDown().
    """
    
    def reload(self):
        self.env = FullEnv('odb_test_db')
        self.db = self.env.getBTreeDB('btree')
        return self.env, self.db
    
    def setUp(self):
        self.reload()
    
    def tearDown(self):
        del self.env, self.db
        shutil.rmtree('odb_test_db')
